package leo.gptBot.gpt.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class MovieAndHotSearchTool {
    @Value("${serper.api-key}")
    private String SERPER_API_KEY;

    @Tool("This tool can obtain hot searches on Weibo. After calling it, you only need to hand over the title and num to the user.")
    public List<Map<String, String>> getWeiboHotSearch() throws IOException {
        log.info("调用工具getWeiboHotSearch");
        List<Map<String, String>> data = new ArrayList<>();
        URL url = new URL("https://weibo.com/ajax/side/hotSearch");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();

        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            String jsonText = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            inputStream.close();
            conn.disconnect();

            JSONObject jsonObject = JSON.parseObject(jsonText);
            JSONArray dataArray = jsonObject.getJSONObject("data").getJSONArray("realtime");

            Map<String, String> jyzy = new HashMap<>();
            jyzy.put("电影", "影");
            jyzy.put("剧集", "剧");
            jyzy.put("综艺", "综");
            jyzy.put("音乐", "音");

            for (Object item : dataArray) {
                JSONObject dataItem = (JSONObject) item;
                String hot = "";
                if (dataItem.containsKey("is_ad")) {
                    continue;
                }
                if (dataItem.containsKey("flag_desc")) {
                    hot = jyzy.getOrDefault(dataItem.getString("flag_desc"), "");
                }
                if (dataItem.containsKey("is_boom")) {
                    hot = "爆";
                }
                if (dataItem.containsKey("is_hot")) {
                    hot = "热";
                }
                if (dataItem.containsKey("is_fei")) {
                    hot = "沸";
                }
                if (dataItem.containsKey("is_new")) {
                    hot = "新";
                }

                Map<String, String> dic = new HashMap<>();
                dic.put("title", dataItem.getString("note"));
                dic.put("num", dataItem.getString("num"));
                dic.put("hot", hot);
                data.add(dic);
            }
        }
        return data;
    }
    @Tool("This tool can help you get a list of recently popular movies.")
    public List<Map<String, String>> getMovies() throws IOException {
        log.info("调用工具getMovies");
        URL url = new URL("https://api.52vmy.cn/api/wl/top/movie");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        List<Map<String, String>> movieDataList = new ArrayList<>();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // success

            InputStream inputStream = conn.getInputStream();
            String jsonText = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            inputStream.close();
            conn.disconnect();

            JSONObject jsonObject = JSON.parseObject(jsonText);

            // Parse JSON response
            JSONArray movieList = jsonObject.getJSONObject("data").getJSONArray("list");


            for (int i = 0; i < movieList.size(); i++) {
                JSONObject movie = movieList.getJSONObject(i);
                String movieName = movie.getJSONObject("movieInfo").getString("movieName");
                String totalBoxOffice = movie.getString("sumBoxDesc");

                Map<String, String> movieData = new HashMap<>();
                movieData.put(movieName, totalBoxOffice);

                movieDataList.add(movieData);
            }

        }
        return movieDataList;
    }
    @Tool("With this tool you can perform Google searches and get some information.")
    public String search(@P("search keyword")String query) throws IOException {
        log.info("调用工具search:"+query);
        String SERPER_GOOGLE_URL = "https://google.serper.dev/search";
        // 创建URL对象
        URL url = new URL(SERPER_GOOGLE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求方法和头信息
        conn.setRequestMethod("POST");
        conn.setRequestProperty("X-API-KEY", SERPER_API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 构建JSON请求体
        JSONObject payload = new JSONObject();
        payload.put("q", query);

        // 发送请求
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = payload.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }
        // 打印并返回响应
        return response.toString();
    }


//    public static void main(String[] args) {
//        MovieAndHotSearchTool weiboHotSearchTool = new MovieAndHotSearchTool();
//        try {
//            List<Map<String, String>> hotSearchData = weiboHotSearchTool.getMovies();
//            String jsonOutput = JSON.toJSONString(hotSearchData);
//            System.out.println(jsonOutput);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
